import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export interface UserInfo {
  username: string
  role: 'teacher' | 'student'
  name: string
}

// 定义测试用户
const testUsers = [
  { username: 'teacher1', password: '123456', role: 'teacher', name: '张老师' },
  { username: 'teacher2', password: '123456', role: 'teacher', name: '李老师' },
  { username: 'student1', password: '123456', role: 'student', name: '王同学' },
  { username: 'student2', password: '123456', role: 'student', name: '赵同学' }
]

export const useUserStore = defineStore(
  'schoolFacilityUser',
  () => {
    const router = useRouter()
    const userInfo = ref<UserInfo | null>(null)
    const isLoggedIn = ref(false)

    // 登录方法
    function login(username: string, password: string): boolean {
      const user = testUsers.find(
        (u) => u.username === username && u.password === password
      )

      if (user) {
        userInfo.value = {
          username: user.username,
          role: user.role as 'teacher' | 'student',
          name: user.name
        }
        isLoggedIn.value = true
        return true
      }
      return false
    }

    // 登出方法
    function logout() {
      userInfo.value = null
      isLoggedIn.value = false
      router.push('/login')
    }

    return {
      userInfo,
      isLoggedIn,
      login,
      logout
    }
  },
  {
    persist: true // 持久化存储
  }
)